#include "xmppcore/xmlwriter.h"

#include <QtGui/QTextDocument>

namespace yoohoo_xmppcore {

XmlWriter::XmlWriter() {
	_inStartElement = false;
}

void XmlWriter::writeAttribute(QString localName, QString value) {
	writeAttribute(QString(), localName, value);
}

void XmlWriter::writeAttribute(QString prefix, QString localName, QString value) {
	if (!_inStartElement) {
		return;
	}

	if (localName.isEmpty())
		return;

	if (value.isEmpty())
		return;

	QString attributeName = prefix.isEmpty() ? localName : prefix.append(':').append(localName);
	_xml.append(' ').
		append(attributeName).
		append("='").
		append(value).
		append('\'');
}

void XmlWriter::writeCharacters(QString characters) {
	writeCharacters(characters, true);
}

void XmlWriter::writeEndElement() {
	if (_elements.isEmpty())
		return;

	if (_xml.isEmpty())
		return;

	QString element = _elements.pop();
	if (_inStartElement) {
		_xml.append("/>");
	} else {
		_xml.append("</").
			append(element).
			append('>');
	}

	_inStartElement = false;
}

void XmlWriter::writeNamespace(QString namespaceUri) {
	if (!_inStartElement)
		return;

	if (namespaceUri.isEmpty())
		return;

	_xml.append(" xmlns='").append(namespaceUri).append('\'');
}

void XmlWriter::writeStartElement(QString localName) {
	writeStartElement(QString(), localName);
}

void XmlWriter::writeStartElement(QString prefix, QString localName) {
	if (localName.isEmpty())
		return;

	if (_inStartElement) {
		_xml.append('>');
	}

	QString element = (prefix.isEmpty() ? localName : prefix.append(':').append(localName));
	_xml.append('<').
		append(element);

	_elements.push(element);
	_inStartElement = true;
}
	
QString XmlWriter::toXml() {
	return _xml;
}
	
void XmlWriter::writePrefix(QString prefix, QString namespaceUri) {
	if (!_inStartElement)
		return;

	if (prefix.isEmpty())
		return;

	if (namespaceUri.isEmpty())
		return;

	_xml.append(" xmlns:").
		append(prefix).
		append("='").
		append(namespaceUri).
		append("'");
}

void XmlWriter::writeEmptyElement(QString localName) {
	writeEmptyElement(QString(), localName);
}
	
void XmlWriter::writeEmptyElement(QString prefix, QString localName) {
	writeStartElement(prefix, localName);
	writeEndElement();
}

void XmlWriter::writeCharacters(QString characters, bool escape) {
	if (_inStartElement) {
		_xml.append('>');
	}

	if (!characters.isEmpty()) {
		if (escape) {
			_xml.append(Qt::escape(characters));
		} else {
			_xml.append(characters);
		}
	}

	_inStartElement = false;
}

void XmlWriter::clear() {
	_elements.clear();
	_xml.clear();
}

}
